package com.tf_cut.admin.backend.controller;

import com.tf_cut.admin.common.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/backend/upload/mobile")
@Slf4j
public class MobileUploadController {

    @Value("${mobile.upload.path}")
    private String filePath;

    private String uploadPath="mobile/upload/";

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {



        if (file.isEmpty()) {
            return Result.of(null,false,"上传失败，请选择文件");
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为：" + fileName);

        // 获取文件的后缀名,比如图片的jpeg,png
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为：" + suffixName);

        // 文件上传后的路径
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("转换后的名称:"+fileName);

        File dir=new File(filePath+uploadPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        File dest = new File(filePath +uploadPath+ fileName);

        try {
            file.transferTo(dest);

            return Result.of(uploadPath+fileName);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.of(null,false,"上传失败");
    }

}
